package com.chenhb.watermarkutils;

import com.chenhb.watermarkutils.bo.WatermarkBo;
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ShapeLineStyle;
import com.spire.doc.documents.ShapeType;
import com.spire.doc.fields.ShapeObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;

/**
 * word添加文字水印工具
 *
 * @author 陈海波
 * @date 2021-04-21
 */
public class WordTextWatermark extends AbstractWatermark {
    /**
     * 给word添加文字水印
     *
     * @param watermarkBo
     * @return
     * @throws Exception
     */
    public static ByteArrayOutputStream mark(WatermarkBo watermarkBo) throws Exception {
        //加载示例文档
        Document doc = new Document();
        doc.loadFromStream(new FileInputStream(watermarkBo.getResourceFile()), FileFormat.Docx);
        //添加艺术字并设置大小
        ShapeObject shape = new ShapeObject(doc, ShapeType.Text_Plain_Text);
        shape.setWidth(watermarkBo.getWidth());
        shape.setHeight(watermarkBo.getHeight());
        //旋转角度
        shape.setRotation(watermarkBo.getDegree());
        //字体
        shape.getWordArt().setFontFamily(watermarkBo.getFontTtf());
        //文字
        shape.getWordArt().setText(watermarkBo.getWatermarkContent());
        //颜色
        shape.setFillColor(watermarkBo.getColor());
        shape.setLineStyle(ShapeLineStyle.Single);
        //new Color(red,green,blue,alpha-透明度)
        shape.setStrokeColor(watermarkBo.getColor());
        shape.setStrokeWeight(1);
        shape.setRotation(watermarkBo.getDegree());
        Section section;
        HeaderFooter header;
        for (int n = 0; n < doc.getSections().getCount(); n++) {
            section = doc.getSections().get(n);
            //获取section的页眉
            header = section.getHeadersFooters().getHeader();
            Paragraph paragraph;
            //添加段落到页眉
            paragraph = header.addParagraph();
            //复制艺术字并设置多行多列位置
            shape = (ShapeObject) shape.deepClone();
            // 纵坐标
            shape.setVerticalPosition(watermarkBo.getOffsetY());
            // 横坐标
            shape.setHorizontalPosition(watermarkBo.getOffsetX());
            paragraph.getChildObjects().add(shape);
        }
        //保存文档
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        doc.saveToStream(output, FileFormat.Docx);
        return output;
    }

}
